import React, { useEffect, useRef, useState } from "react";
import { Drawer, Input, Radio, Space, Typography, message } from "antd";

import ProTable, { ProTableRef } from "@/components/TablePro"; // 导入封装的表格组件
import Add from "./add";
import { httpClient } from "@/common/httpClient";
import {
  DeviceRegisterField,
  createDeviceRegisterField,
  PrimaryKey,
  Mode,
} from "./deviceNodesFields";

import { Fields, TableAction } from "@/types/public";
import { HearderType } from "@/common/common";
import {
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import modal from "antd/es/modal";
import TextArea from "antd/es/input/TextArea";
interface ProjectListsProps {
  groupId?: number;
  slaveId?: number;
  deviceId?: number;
}
const ProjectLists: React.FC<ProjectListsProps> = ({
  groupId,
  slaveId,
  deviceId,
}) => {
  const tableRef = useRef<ProTableRef>(null);
  const [columns, setColumns] = useState<Fields[]>([]);
  const [updateData, setUpdateData] = useState<DeviceRegisterField>();
  const [addVisible, setAddVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [projectName, setProjectName] = useState("");
  const [open, setOpen] = useState(false);
  let mode: any,
    setMode: any,
    modeValue: any,
    setModeValue: any,
    resValue: any,
    setResValue: any;
  useEffect(() => {
    if (tableRef.current && groupId !== undefined && slaveId !== undefined) {
      tableRef.current.refresh();
    }
  }, [groupId, slaveId]);

  const CreateSendContent: React.FC<{ record: DeviceRegisterField }> = ({
    record,
  }) => {
    [mode, setMode] = useState<Mode>("R");
    [modeValue, setModeValue] = useState<string>("01");
    [resValue, setResValue] = useState<string>("");

    if (!record) return <></>;
    const actions = record.rwPermission
      .split(",")
      .map((v) => ({ label: v.trim(), value: v.trim() }));
    const actionOptions =
      record.getter.extendsjsonobject?.options?.[0]?.choices;
    return (
      <Space size={10} direction="vertical" style={{ width: "100%" }}>
        <h3>请选择发送类型:</h3>
        <Radio.Group
          value={mode}
          optionType="button"
          buttonStyle="solid"
          options={actions}
          onChange={(e) => {
            setMode(e.target.value as Mode);
          }}
        ></Radio.Group>
        {mode === "W" && (
          <TextArea
            style={{ width: "100%" }}
            rows={4}
            placeholder="请输入发送内容"
          />
        )}
        {mode == "C" && (
          <>
            <h3>操作功能</h3>
            <Radio.Group
              value={modeValue}
              options={actionOptions}
              onChange={(e) => {
                setModeValue(e.target.value);
              }}
            ></Radio.Group>
          </>
        )}
      </Space>
    );
  };

  const tableAction: TableAction<DeviceRegisterField> = {
    detail: (record: DeviceRegisterField) => {
      setUpdateData(record);
      setOpen(true);
    },
    add: () => {
      setUpdateData(undefined);
      setAddVisible(true);
    },
    edit: (record: DeviceRegisterField) => {
      record.extents = {
        id: record?.id,
        groupId: groupId,
        slaveId: slaveId,
        deviceId: deviceId,
        mode: "R",
        value: "1",
      };
      setUpdateData(record);
      setAddVisible(true);
    },
    delete: async (rows: DeviceRegisterField[]) => {
      let res = await httpClient.post(
        "/admin/device_register/delete",
        { ids: rows.join(",") },
        {
          headers: { "Content-Type": HearderType[0] },
        }
      );
      if (res.data.data) tableRef.current?.refresh();
    },
    migrate: () => {
      setAddVisible(true);
    },
    custom: (record?: DeviceRegisterField) => {
      //选择读或者写
      if (record) {
        modal.confirm({
          title: "确认发送命令-" + record?.registerName,
          icon: <ExclamationCircleOutlined />,
          content: <CreateSendContent record={record} />,
          okText: "确认",
          cancelText: "取消",
          async onOk() {
            let res = await httpClient.post(
              "/admin/device_register/send",
              {
                id: record?.id,
                groupId: groupId,
                slaveId: slaveId,
                deviceId: deviceId,
                mode: mode,
                value: modeValue,
              },
              {
                headers: { "Content-Type": HearderType[0] },
              }
            );
            modal.confirm({
              icon: <CheckCircleOutlined color="green" />,
              title: record?.registerName,
              content: <div>结果{res.data.data.result}</div>,
            });

            // return false;
            // return res;
          },
        });
      }
    },
  };
  //   const columns: any[] = createDeviceRegisterField(tableAction);
  // 异步加载 columns
  useEffect(() => {
    createDeviceRegisterField(tableAction).then((columns: Fields[]) => {
      setColumns(columns);
    });
  }, []);
  const handleSubmit = async (e: any) => {
    let res = await httpClient.post(
      updateData
        ? "/admin/device_register/update"
        : "/admin/device_register/create",
      updateData ? e : [e],
      updateData
        ? {
            headers: { "Content-Type": HearderType[0] },
          }
        : undefined
    );
    if (res.data.data) tableRef.current?.refresh();
  };
  const handleCloseAdd = () => {
    setAddVisible(false);
  };

  // 模拟API请求
  const fetchProjects = async (params: any) => {
    return await httpClient.get("admin/device_register/lists", {
      ...params,
      groupId: groupId || params.groupId,
    });
  };

  function deleteProject(id: any): void {
    throw new Error("Function not implemented.");
  }

  function migrateProject(id: any): void {
    throw new Error("Function not implemented.");
  }

  return (
    <div id="app-project" className="app-content">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        {/* 项目表格 */}
        <ProTable<DeviceRegisterField>
          request={fetchProjects}
          tableAction={tableAction}
          columns={columns}
          rowKey={PrimaryKey}
          searchable
          ref={tableRef}
          sticky
          resizable
          debounceWait={800}
        />
      </Space>
      <Add
        initialData={updateData}
        visible={addVisible}
        onClose={handleCloseAdd}
        onSubmit={handleSubmit}
        columns={columns}
      />
    </div>
  );
};

export default ProjectLists;
